package cn.iwit.ctl.sys;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.iwit.model.Constant;
import cn.iwit.model.SysUser;
import cn.iwit.model.UserInfo;
import cn.iwit.srv.sys.SysUserService;
import cn.iwit.util.ApplicationContextUtils;
import cn.iwit.util.BusiException;
import cn.iwit.util.FuncUtil;
import cn.iwit.util.HttpUtil;
import cn.iwit.util.JsonResult;
import cn.iwit.util.MD5;
import cn.iwit.util.PageInfo;
import cn.iwit.util.TokenUtils;

import com.google.code.kaptcha.impl.DefaultKaptcha;

@RestController
public class LoginController {
	
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private SysUserService sysUserService;
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public JsonResult login(HttpServletRequest request,String username,String password,String identifycode) throws Exception{
		 logger.info("login param:{},{},{}",username,password,identifycode);
		 JsonResult result = new JsonResult();
		 Long time = System.currentTimeMillis();
		 String access_token =  TokenUtils.getToken(username  + time);
		 SysUser sysUser = new SysUser();
		 sysUser.setUsername(username);
		 sysUser.setPassword(MD5.getMD5(password));
		 
		 PageInfo<SysUser>  page = sysUserService.findUsers(sysUser, new PageInfo<SysUser>(1,1, ""));
		 
		 if(page.getList().size()==0){
			 result.setResult(1);
			 result.setMessage("用户名或密码错误！");
			 return result;
		 }else{
			 UserInfo userInfo = sysUserService.loadUserInfo(page.getList().get(0).getUserid());
	         HttpUtil.setAttribute(Constant.ACCESS_TOKEN, access_token);
	         HttpUtil.setAttribute(Constant.USERINFO, userInfo);
	         
	         Map<String, String> map = new HashMap<>();
	         map.put(Constant.ACCESS_TOKEN, access_token);
	         result.setData(map);
	         result.setResult(0);
	         result.setMessage("登录成功！");
		 }
         return result;
	}
	
    /**
     * 登出
     *
     * @param request
     * @param response
     * @return
     * @throws BusiException 
     */
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public JsonResult logou(HttpServletRequest request, HttpServletResponse response) throws BusiException {
        JsonResult result = new JsonResult();
        HttpUtil.removeAttribute(Constant.ACCESS_TOKEN);
        request.getSession().removeAttribute("user");
        return result;
    }
	
	 /**
     * 获取验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/identifycode")
    public String getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //Map<String, Object> result = new HashMap<String, Object>();
        DefaultKaptcha captchaProducer = ApplicationContextUtils.getApplicationContext().getBean(DefaultKaptcha.class);
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        if (logger.isDebugEnabled())
        	logger.debug("生成的验证码是{}", capText);
       HttpUtil.setAttribute(Constant.PENSION_IDENTIFYCODE, capText);
        
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
    
    @RequestMapping(value = "/sys/func/thisFuncListByUser")
    public JsonResult thisFuncListByUser(HttpServletRequest request,Long siteid) throws BusiException  {
    	 JsonResult result = new JsonResult();
    	 UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
    	 Map<String,Object> map = new HashMap<>();
         map.put("func", FuncUtil.getFatherNode(userInfo.getSysFuncs()));
         result.setData(map);
         return result;
    }
    
}
